package com.example.demo;

import java.io.IOException;
import java.net.Socket;
import java.lang.Thread;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class LightDivece extends Activity {
	private SeekBar seekbar;
	private TextView textValue;
	private Myapplication app;
	public ImageButton imageButton;
	private CheckBox checkboxon;
	private CheckBox checkboxoff;
	private CheckBox checkboxauto;
	private EditText texttimeon;
	private EditText texttimeoff;
	private Socket sc;
	private boolean status1;
	private Button Select;
	private Button Back;
	public TextView title;
	// private int progress= 30;
	// private OutputStreamWriter out;
	private Protocol protocol = new Protocol();
	private String status = "";
	private String timeon = "";
	private String timeoff = "";
	private String auto = "";
	private String progress = "";
	private String settimeon = "";
	private String settimeoff = "";
	private Integer position = 0;
	private ProgressDialog waitting;
	private String ackstring = "";
	private Integer preSeekbar;
	private Handler handler= new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			   case 0:
				   imageButton
						.setImageResource(R.drawable.download);
					status1 = false;
				   break;
			   case 1:
				imageButton
							.setImageResource(R.drawable.light);
					status1 = true;
					break;
			   case 2:
				   seekbar.setProgress(preSeekbar);
				   break;
			
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_light_divece);
		app = (Myapplication) getApplication();
		sc = app.getSocket();
		imageButton = (ImageButton) findViewById(R.id.imageButton1);
		seekbar = (SeekBar) findViewById(R.id.seekBar1);
		textValue = (TextView) findViewById(R.id.textView3);
		Select = (Button) findViewById(R.id.button1);
		Back = (Button) findViewById(R.id.buttonback);
		title = (TextView) findViewById(R.id.textView1);
		checkboxon = (CheckBox) findViewById(R.id.checkBoxon);
		checkboxoff = (CheckBox) findViewById(R.id.checkBoxoff);
		checkboxauto = (CheckBox) findViewById(R.id.checkBoxauto);
		texttimeon = (EditText) findViewById(R.id.texttimeon);
		texttimeoff = (EditText) findViewById(R.id.texttimeoff);

		seekbar.setMax(100);
		Bundle receiveBundle = this.getIntent().getExtras();
		status = receiveBundle.getString("status");
		settimeoff = receiveBundle.getString("settimeoff");
		timeoff = receiveBundle.getString("timeoff");
		settimeon = receiveBundle.getString("settimeon");
		timeon = receiveBundle.getString("timeon");
		auto = receiveBundle.getString("auto");
		progress = receiveBundle.getString("progress");
		position = receiveBundle.getInt("position");
		SharedPreferences editPreference = this.getSharedPreferences(
				"DATAUSER", Activity.MODE_PRIVATE);

		String test = editPreference.getString(
				"LIGHT" + String.valueOf(position + 1),
				"Light" + String.valueOf(position + 1));
		// set title
		title.setText(test);
		Log.i("test", test);
		// set seekbar
		seekbar.setMax(100);
		seekbar.setProgress(Integer.parseInt(progress));
		if (progress.startsWith("0")) {
			if (progress.startsWith("00")) {
				textValue.setText(progress.substring(2) + "%");
			} else
				textValue.setText(progress.substring(1) + "%");
		} else
			textValue.setText(progress + "%");
		// set status

		if (status.equals("0") == true) {

			imageButton.setImageResource(R.drawable.download);
			status1 = false;
		} else {

			imageButton.setImageResource(R.drawable.light);
			status1 = true;
		}
		// set checkbox time on
		if (settimeon.equals("1") == true) {
			checkboxon.setChecked(true);

		} else {
			checkboxon.setChecked(false);
		}
		// set checkbox time off
		if (settimeoff.equals("1") == true) {
			checkboxoff.setChecked(true);

		} else {
			checkboxoff.setChecked(false);
		}
		// set checbok auto
		if (auto.equals("1") == true) {
			checkboxauto.setChecked(true);

		} else {
			checkboxauto.setChecked(false);
		}
		// set text time on
		texttimeon.setText(timeon);
		// set text time off
		texttimeoff.setText(timeoff);

		seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            
			public void onStopTrackingTouch(SeekBar seekBar) {
              waitting = ProgressDialog.show(LightDivece.this,"", "Watting...",true);
               new Thread(new Runnable() {
				
				public void run() {
				    try {
						ackstring = protocol.Receive(sc);
						waitting.dismiss();
						if(ackstring.equals("<LIGHT_ACK>NO</LIGHT_ACK>")){
							handler.sendEmptyMessage(2);
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}).start();
				try {
					if (seekBar.getProgress() == 100)
						protocol.sendMessages(sc,
								  String.valueOf(seekBar.getProgress()),
								Protocol.USER_PROGRESS);
					else if (seekBar.getProgress() > 9)
						protocol.sendMessages(sc,
								 "0"+ String.valueOf(seekBar.getProgress()),
								Protocol.USER_PROGRESS);
					else 
						protocol.sendMessages(sc,
								 "00"+ String.valueOf(seekBar.getProgress()),
								Protocol.USER_PROGRESS);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
	              preSeekbar = seekbar.getProgress();


			}

			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
				textValue.setText(progress + "%");

			}
		});

		imageButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				waitting = ProgressDialog.show(LightDivece.this, "",
						"Waitting..", true);
			
				new Thread(new Runnable() {

					public void run() {
					    
						changeState();
					}

				}).start();
		 
				
			}
			
		});
		Back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				setResult(RESULT_OK, intent);
				finish();

			}
		});
		Select.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(LightDivece.this, SettingUser.class);
				startActivity(intent);

			}
		});
		checkboxon.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (checkboxon.isChecked()) {
					try {
						protocol.sendMessages(sc, "1"
								+ texttimeon.getText().toString(),
								Protocol.TIMEON);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					try {
						protocol.sendMessages(sc, "0"
								+ texttimeon.getText().toString(),
								Protocol.TIMEON);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
		});
		checkboxoff.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (checkboxoff.isChecked()) {
					try {
						protocol.sendMessages(sc, "1"
								+ texttimeoff.getText().toString(),
								Protocol.TIMEOFF);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} else {
					try {
						protocol.sendMessages(sc, "0"
								+ texttimeoff.getText().toString(),
								Protocol.TIMEOFF);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_light_divece, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu:
			Intent intent = new Intent(LightDivece.this, SettingUser.class);
			startActivity(intent);
			break;
		}
		return false;
	}
	public void changeState(){
		
		if (status1 == true) {

			try {

				protocol.sendMessages(sc, "OFF",
						Protocol.USER_STATUS);
				ackstring = protocol.Receive(sc);
				Log.i("ack", ackstring);
				waitting.dismiss();
				if (ackstring
						.equals("<LIGHT_ACK>YES</LIGHT_ACK>")) {
				//	imageButton
				//		.setImageResource(R.drawable.download);
				//	status1 = false;
					handler.sendEmptyMessage(0);
				
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			try {

				protocol.sendMessages(sc, "ON",
						Protocol.USER_STATUS);
				ackstring = protocol.Receive(sc);
				Log.i("ack", ackstring);
				waitting.dismiss();
				if (ackstring
						.equals("<LIGHT_ACK>YES</LIGHT_ACK>")) {
				//	imageButton
				//		.setImageResource(R.drawable.light);
				//	status1 = true;
					handler.sendEmptyMessage(1);
					
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		
	}
}

